import 'dart:async';
import 'dart:math';

import 'package:EZ_Batter/src/home/home_util.dart';
import 'package:EZ_Batter/src/tool/model.dart';
import 'package:fl_chart/src/chart/base/axis_chart/axis_chart_data.dart';
import 'package:fl_chart/src/chart/base/base_chart/fl_touch_event.dart';
import 'package:fl_chart/src/chart/line_chart/line_chart_data.dart';
import 'package:flutter/material.dart';
import 'package:flutter_kit_plus/flutter_kit.dart';
import 'package:get/get.dart';

import '../bluetooth/send_data.dart';
import '../tool/assets.dart';
import 'animation_logo.dart';
import 'bottom_bar.dart';
import 'detail_list.dart';
import 'line_char.dart';

class MyHome extends StatefulWidget {
  MyHome({super.key});

  @override
  State<MyHome> createState() => _MyHomeState();
}

class _MyHomeState extends State<MyHome> implements LineCharDataSource, LineCharDelegate {
  final GlobalController modelController = Get.put(GlobalController());
  int timestampSeconds = 0;
  String appVersion = '';
  List<double> defaultLeftTitles = [11.6, 12, 12.4, 12.8, 13.2, 13.6, 14.0, 14.4, 14.8, 15.2, 15.6];
  List<double> defaultRightTitles = [0, 0.4, 0.8, 1.2, 1.6, 2.0, 2.4, 2.8, 3.2, 3.6, 4.0];
  late final HomeUtil utilV;
  late final HomeUtil utilA;
  List<double> get showLeftYaxis {
    if (BluetoothManager().connectedDeviceList.isEmpty || utilV.validData.isEmpty) {
      return defaultLeftTitles;
    } else {
      double avgVal = (utilV.maxValue - utilV.minValue) / (defaultLeftTitles.length - 1);
      return List.generate(defaultLeftTitles.length, ($0) {
        return (utilV.minValue + $0 * avgVal).roundDouble(2);
      });
    }
  }

  List<double> get showRightYaxis {
    if (BluetoothManager().connectedDeviceList.isEmpty || utilA.validData.isEmpty) {
      return defaultRightTitles;
    } else {
      double max_temp = utilA.validData.reduce(max);
      double min_temp = utilA.validData.reduce(min);
      if (max_temp == min_temp && max_temp == 0.0) {
        return defaultRightTitles;
      } else {
        double avgVal = (utilA.maxValue - utilA.minValue) / (defaultRightTitles.length - 1);
        return List.generate(defaultRightTitles.length, ($0) {
          return (utilA.minValue + $0 * avgVal).roundDouble(2);
        });
      }
    }
  }

  @override
  void initState() {
    timestampSeconds = DateTime.now().millisecondsSinceEpoch;
    utilV = HomeUtil(2);
    utilA = HomeUtil(2);
    super.initState();
    getAPPVersion();
    listen();
    listenBluetooth(context);

    Timer.periodic(const Duration(seconds: 2), (timer) {
      timestampSeconds = DateTime.now().millisecondsSinceEpoch;
      if (BluetoothManager.instance.connectedDeviceList.isNotEmpty) {
        SendData.send('基本信息', null);
        SendData.send('查询电池', []); //查询电池
        update();
      }
    });
  }

  void update() {
    setState(() {
      utilV.update(GlobalModel().v);
      utilA.update(GlobalModel().a);
    });
  }

  Future<void> getAPPVersion() async {
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    setState(() => appVersion = packageInfo.version);
  }

  @override
  Widget build(BuildContext context) {
    final Size screenSize = MediaQuery.of(context).size;
    // 获取上下安全区域的高度
    final double topSafeAreaHeight = MediaQuery.of(context).padding.top;
    final double bottomSafeAreaHeight = MediaQuery.of(context).padding.bottom;

    // /禁止掉android侧滑，退出app
    return PopScope(
      canPop: false,
      child: Scaffold(
        appBar: null,
        extendBodyBehindAppBar: true, // 让 body 完全覆盖 AppBar
        resizeToAvoidBottomInset: false, // 关闭键盘弹出时自动调整大小
        body: SizedBox(
          width: screenSize.width,
          height: screenSize.height + 20,
          child: Stack(
            children: [
              ///背景
              Positioned.fill(child: Image.asset(assets.bg, fit: BoxFit.cover)),
              Positioned.fill(
                child: Column(
                  children: [
                    SizedBox(height: topSafeAreaHeight),

                    ///logo
                    Flexible(flex: 1, child: Center(child: Image.asset(assets.logo))),

                    ///动画
                    const Flexible(flex: 4, child: AnimationLogo()),

                    ///列表
                    const Flexible(flex: 3, child: DetailList()),

                    ///折线图
                    Flexible(flex: 8, child: LinecharBgView(delegate: this, dataSource: this)),

                    ///底部按钮
                    const Flexible(flex: 2, child: BottomBar()),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  @override
  List<FlSpot> allSpotsForLineInSection(int section) {
    if (showLeftYaxis.first == 11.6) {
      print('object');
    }
    if (section == 0) {
      return utilA.validData.asMap().entries.map(($0) {
        double s = utilA.gap == 0 ? 0 : utilV.gap / utilA.gap;
        if ($0.value < 0) {
          return FlSpot($0.key.toDouble(), ($0.value.toDouble() * s).roundDouble(1) + utilV.maxValue);
        } else {
          return FlSpot($0.key.toDouble(), ($0.value.toDouble() * s).roundDouble(1));
        }
        // return FlSpot($0.key.toDouble(), 0);
      }).toList();
    } else {
      return utilV.validData.asMap().entries.map(($0) {
        return FlSpot($0.key.toDouble(), $0.value.toDouble());
        // return FlSpot($0.key.toDouble(), 0);
      }).toList();
    }
  }

  @override
  List<Color> colorsForLineBarInSection(int section) {
    Color color = section == 0 ? Color_theme : Colors.green;
    return [color];
  }

  @override
  List<Color> belowColorsForLineBarInSection(int section) {
    Color color = section == 0 ? Color_theme.withOpacity(0.2) : Colors.green.withOpacity(0.2);
    return [color];
  }

  @override
  int numbersOfLine() {
    return 2;
  }

  @override
  Widget? textForBottomAxis(int section, double value, TitleMeta meta, double chartWidth) {
    int v = value.toInt();
    if (v != 0 && (v + 1) % 20 != 0) {
      return null;
    }
    DateTime dateTime =
        DateTime.fromMillisecondsSinceEpoch(timestampSeconds - (100 - (v == 0 ? 0 : v + 1)) * 60 * 1000);
    String formattedTime = "${dateTime.hour.toString()}:${dateTime.minute.toString().padLeft(2, '0')}";
    return Text(formattedTime, style: const TextStyle(color: Colors.white, fontSize: 10));
  }

  @override
  Widget? textForLeftAxis(int section, double value, TitleMeta meta, double chartWidth) {
    double v = value.roundDouble(2);
    return showLeftYaxis.contains(v) ? Text('${v}', style: const TextStyle(color: Colors.white, fontSize: 10)) : null;
  }

  @override
  Widget? textForRightAxis(int section, double value, TitleMeta meta, double chartWidth) {
    ///用value在左侧y轴文本showLeftYaxis的下标位置，获取当前右侧y轴该显示的下标，并映射出来
    double v = value.roundDouble(2);
    if (showLeftYaxis.contains(v)) {
      int index = showLeftYaxis.indexWhere(($0) => $0 == v);
      return Text('${showRightYaxis[index]}', style: const TextStyle(color: Colors.white, fontSize: 10));
    } else {
      return null;
    }
  }

  @override
  FlLine? drawHorizontalGridLine(double value) {
    return null;
  }

  @override
  FlLine? drawVerticalGridLine(double value) {
    return null;
  }

  @override
  bool showHorizontalGridLine(double value) {
    return true;
  }

  @override
  bool showVerticalGridLine(double value) {
    return true;
  }

  @override
  void touchForLineBarInSection(FlTouchEvent event, LineTouchResponse? response) {
    print('object===================>   ${event.localPosition}');
  }

  @override
  Widget widgetLeftInLineChar() {
    // return const Text('左边的组件');
    return Container();
  }

  @override
  Widget widgetRightInLineChar() {
    // return const Text('右边的组件');
    return Container();
  }

  @override
  Widget widgetTopInLineChar() {
    return Container(
      padding: const EdgeInsets.only(left: 10, right: 10),
      child: const Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text('Voltage/V'),
          Text('Current/A'),
        ],
      ),
    );
  }

  @override
  Widget widgetBottomInLineChar() {
    Widget item(String content, Color color) {
      return Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Container(
            height: 8,
            width: 8,
            decoration: BoxDecoration(color: color, borderRadius: BorderRadius.circular(4)),
          ),
          const SizedBox(width: 5),
          Text(content),
        ],
      );
    }

    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceAround,
      children: [item('Total Voltage', Colors.green), item('Current', Color_theme), Text('Version :v$appVersion')],
    );
  }

  @override
  double? intervalOfGridYAxis() {
    return (showLeftYaxis.reduce(max) - showLeftYaxis.reduce(min)) / 10.0;
  }

  @override
  Offset? limitYAxis() {
    return Offset(showLeftYaxis.first, showLeftYaxis.last);
  }
}

///蓝牙的一些监听
extension _MyHomeStateExtesion on _MyHomeState {
  void listenBluetooth(BuildContext context) {
    ///监听蓝牙外设连接状态
    BluetoothManager.instance.connectionStateStream.listen((value) {
      var state = value.values.first;
      switch (state) {
        case BluetoothConnectionState.connected:
          EasyLoading.showSuccess('Connect successfully');
          listen();
          SendData.send('基本信息', null);
          SendData.send('查询电池', []); //查询电池
        case BluetoothConnectionState.disconnected:
          EasyLoading.showSuccess('disConnected!', duration: const Duration(milliseconds: 1500));
          modelController.updateDefault((model) {
            model.v = 0;
          });
          update();
        case BluetoothConnectionState.connecting:
          break;
        case BluetoothConnectionState.disconnecting:
          print('设备断开连接中');
          break;
      }
    });

    ///监听蓝牙广播状态
    BluetoothManager.instance.bluetoothStateStream.listen((state) {
      switch (state) {
        case BluetoothAdapterState.on:
          break;
        case BluetoothAdapterState.off:
          EasyLoading.showInfo('Bluetooth turned off');
        default:
      }
    }, onError: (error) {
      EasyLoading.showInfo('${error.message}');
    });
  }

  void listen() {
    ///监听数据回调
    BluetoothManager.instance.read(
        service_uuid: read_service,
        characteristics_uuid: read_uuid,
        onResponse: (data) {
          print('收到蓝牙上传的数据是 == ${data.toHexstr(' |')}');
          GlobalModel.update(data);
          modelController.updateDefault((model) {
            model.rsoc = GlobalModel().rsoc;
          });
        });
  }
}
